package org.wanho.sms.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * JDBC工具类
 */
public class JdbcUtil {
	
	private static DataSource datasource;
	private static ThreadLocal<Connection> local = new ThreadLocal<Connection>();
	
	
	static{
		try {
			Properties p = new Properties();
			p.load(JdbcUtil.class.getClassLoader().getResourceAsStream("datasource.properties"));
			datasource = DruidDataSourceFactory.createDataSource(p);
		}catch (Exception e) {
			throw new ExceptionInInitializerError("JdbcUtil初始化失败："+e);
		}
	}
	
	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection(){
		Connection conn = local.get();
		try {
			if(conn == null){
				conn = datasource.getConnection();
				local.set(conn);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭Connection
	 */
	public static void close(){
		Connection conn = local.get();
		if(conn != null){
			try {
				conn.close(); // 释放连接
			} catch (SQLException e) {
				e.printStackTrace();
			} 
			local.remove(); // 将ThreaLocal清空
		}
	}
	
	
	/**
	 * 关闭资源
	 */
	public static void close(Statement stmt, ResultSet rs){
		try {
			if(rs!=null){
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
